package com.clwl.supervise.superviseapp.service.inspect;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.entity.base.*;
import com.clwl.supervise.superviseapp.entity.risk.JgPointDistance;
import com.clwl.supervise.superviseapp.entity.supervise.*;
import com.clwl.supervise.superviseapp.mapper.base.JgProcessCodeMapper;
import com.clwl.supervise.superviseapp.mapper.base.TcCompanyMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsDeptMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsUserMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.*;
import com.clwl.supervise.superviseapp.service.SequenceService;
import com.clwl.supervise.superviseapp.service.base.BaseDataService;
import com.clwl.supervise.superviseapp.util.UserHelper;
import com.clwl.supervise.superviseapp.util.file.FileResultEntity;
import com.clwl.supervise.superviseapp.util.file.FileUploadEnum;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FlightPlanService {


    @Resource
    private JgProcessCodeMapper jgProcessCodeMapper;

    @Resource
    private JgClassifySpxsMapper classifySpxsMapper;
    @Resource
    private JgClassifyCyfwMapper classifyCyfwMapper;
    @Resource
    private JgClassifySpscCompMapper classifySpscCompMapper;
    @Resource
    private TsUserMapper userMapper;
    @Resource
    private JgDailyCheckMapper dailyCheckMapper;
    @Resource
    private JgSchemePlanCheckMapper schemePlanCheckMapper;
    @Resource
    private JgFlightPlanCheckMapper flightPlanCheckMapper;
    @Resource
    private JgFlightPlanUserMapper flightPlanUserMapper;
    @Resource
    private JgFlightStandardMapper flightStandardMapper;
    @Resource
    private JgFlightContentMapper flightContentMapper;
    @Resource
    private TcCompanyMapper tcCompanyMapper;
    @Resource
    private JsEntAnomalyMapper jsEntAnomalyMapper;

    @Resource
    private JgRectificationMapper rectificationMapper;

    @Resource
    private JgCheckMissingMapper jgCheckMissingMapper;

    @Resource
    private JgCheckProblemMapper jgCheckProblemMapper;


    @Resource
    private JgRectificationContentMapper rectificationContentMapper;

    @Resource
    private JgInvestigationMapper investigationMapper;

    @Resource
    private JgInvestigationSetMapper investigationSetMapper;

    @Resource
    private JgInvestigationContentMapper investigationContentMapper;
    @Resource
    private JgFlightContentFileMapper contentFileMapper;

    @Resource
    private JgScDynamicScoringMapper scDynamicScoringMapper;
    @Resource
    private BaseDataService baseDataService;
    @Resource
    private TsDeptMapper tsDeptMapper;
    @Resource
    private SequenceService sequenceService;


    public IPage<Map<String, Object>> selectCompanyPage(Integer pageNum, Integer pageSize, CommonSearchEntity params) {
        params.setCreatorId(UserHelper.getUserId());
        String dataRange = UserHelper.getUserInfo().getDataRange();
        params.setUserId(UserHelper.getUserId());
        params.setDataRange(dataRange);
        params.setDeptId(UserHelper.getUserInfo().getDeptId());
        params.setBusinessFormatRange(UserHelper.getUserInfo().getBusinessFormatRange());
        String deptType = "3";
        if ("0".equals(dataRange)) {
            deptType = "0";
        } else if ("1".equals(dataRange)) {
            deptType = "1";
        } else if ("2".equals(dataRange)) {
            deptType = "2";
        } else if ("3".equals(dataRange)) {
            deptType = "2";
        }
        TsDept dataDeptEntity = tsDeptMapper.getDataParentDeptId(UserHelper.getUserInfo().getDeptId(), deptType);
        if (dataDeptEntity != null) {
            params.setDataDeptId(dataDeptEntity.getId());
        } else {
            params.setDataDeptId(UserHelper.getUserInfo().getDeptId());
        }
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("2") >= 0 || UserHelper.getUserInfo().getBusinessFormatRange().indexOf("3") >= 0) {
            params.setIsSc("1");
        } else {
            params.setIsSc("0");
        }
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        //iPage.setOptimizeCountSql(false);
        //iPage.setSearchCount(false);
        log.info("type:{}", params.getType());
        if ("0".equals(params.getType())) {
            //待检查
            return flightPlanCheckMapper.selectCompanyList(iPage, params);
        } else {
            //已检查
            return flightPlanCheckMapper.selectCheckResult(iPage, params);
        }
    }

    /**
     * 获取检查时候的显示信息
     *
     * @param checkId 检查单id
     * @return
     */
    public JgFlightPlanCheck getSchemeCheckInfo(Long checkId) {
        JgFlightPlanCheck flightPlanCheck = flightPlanCheckMapper.selectById(checkId);
        flightPlanCheck.setManageStatus(flightPlanCheck.getManageStatus() == null ? "0" : flightPlanCheck.getManageStatus());
        flightPlanCheck.setDelayCheck(flightPlanCheck.getDelayCheck() == null ? "0" : flightPlanCheck.getDelayCheck());
        flightPlanCheck.setVerificationRecords("");
        TcCompany company = tcCompanyMapper.selectById(flightPlanCheck.getCompanyId());
        flightPlanCheck.setSuperviseDeptName(company.getDeptName());
        JgPointDistance distance = baseDataService.getCheckDistance(flightPlanCheck.getCompanyId() + "");
        flightPlanCheck.setDistance(distance.getDistance());
        List<JgFlightPlanUser> schemePlanUser = flightPlanUserMapper.selectByPlanId(flightPlanCheck.getPlantId());
        flightPlanCheck.setFlightPlanUserList(schemePlanUser);
        flightPlanCheck.setLngLat(company.getLngLat());
        flightPlanCheck.setCompanyAddress(company.getAddress());
        //获取企业的一级业态信息
        if (company.getSupProcess() != null) {
            JgProcessCode processCode = jgProcessCodeMapper.selectByCode(company.getSupProcess());
            flightPlanCheck.setCompanyTypeName(processCode.getName());
            switch (company.getSupProcess()) {
                case "spxs":
                    JgClassifySpxs classifySpxs = classifySpxsMapper.selectByProcessCodeAndCompanyType(processCode.getId(), company.getCompanyTypeId());
                    flightPlanCheck.setCompanyTypeName(flightPlanCheck.getCompanyTypeName() + (classifySpxs == null ? "" : "/" + classifySpxs.getName()));
                    break;
                case "cyfw":
                    JgClassifyCyfw classifyCyfw = classifyCyfwMapper.selectByProcessCodeAndCompanyType(processCode.getId(), company.getCompanyTypeId());
                    flightPlanCheck.setCompanyTypeName(flightPlanCheck.getCompanyTypeName() + (classifyCyfw == null ? "" : "/" + classifyCyfw.getName()));
                    break;
                case "spsc":
                    Map<String, Object> classifysc = classifySpscCompMapper.selectByCompanyId(company.getId(), processCode.getId(), "1", "0");
                    flightPlanCheck.setCompanyTypeName(flightPlanCheck.getCompanyTypeName() + (classifysc == null ? "" : "/" + classifysc.get("NAME").toString()));
                    break;
                case "tssc":
                    Map<String, Object> classifyts = classifySpscCompMapper.selectByCompanyId(company.getId(), processCode.getId(), "1", "1");
                    flightPlanCheck.setCompanyTypeName(flightPlanCheck.getCompanyTypeName() + (classifyts == null ? "" : "/" + classifyts.get("NAME").toString()));
                    break;
            }
        }
        flightPlanCheck.setCompanyNatureBusiness(company.getBusinessScope());
        flightPlanCheck.setCompanyContact(company.getContact());
        flightPlanCheck.setCompanyContactPhone(company.getContactPhone());
        if (!("spsc".equals(company.getSupProcess()) || "tssc".equals(company.getSupProcess())) && company.getCompanyTypeId() == null) {
            throw new RuntimeException("企业业态信息为空,无法获取检查内容!");
        }
        String supProcess = company.getSupProcess();
        flightPlanCheck.setSupProcess(supProcess);
        //查看当前企业是否之前填写了检查信息
        try {
            //获取检查内容
            List<JgFlightStandard> flightStandardList = flightStandardMapper.selectByCheckId(flightPlanCheck.getId());
            //风险信息
            Map<String, String> riskMap = baseDataService.riskInfo(company.getId());
            List<String> riskCode = new ArrayList<>();
            Set<String> riskKeySet = riskMap.keySet();
            for (String riskKey : riskKeySet) {
                if (!"0".equals(riskMap.get(riskKey))) {
                    riskCode.add(riskKey);
                }
            }
            List<Map<String, Object>> checkMissingListAll = jgCheckMissingMapper.selectMapList();
            List<Map<String, Object>> checkProblemListAll = jgCheckProblemMapper.selectMapList();

            for (JgFlightStandard jgFlightStandard : flightStandardList) {
                List<JgFlightContent> flightContentList = flightContentMapper.selectByStandardId(jgFlightStandard.getId(), riskCode);
                for (JgFlightContent content : flightContentList) {
                    //获取合理缺项
                    List<Map<String, Object>> checkMissingList = checkMissingListAll.stream().filter(map -> StringUtils.equals(content.getContentId() + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
                    //List<Map<String, Object>> checkMissingList = jgCheckMissingMapper.selectByContentId(content.get("ID"));
                    for (Map<String, Object> map : checkMissingList) {
                        map.put("is_selected", false);
                        if (content.getMissingItemContent() != null) {
                            if (content.getMissingItemContent().equals(String.valueOf(map.get("describe")))) {
                                map.put("is_selected", true);
                            }
                        }
                    }

                    content.setCheckMissingList(checkMissingList);
                    //获取content的问题描述选项
                    List<Map<String, Object>> checkProblemList = checkProblemListAll.stream().filter(map -> StringUtils.equals(content.getContentId() + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
                    // List<Map<String, Object>> checkProblemList = jgCheckProblemMapper.selectByContentId(content.get("ID"));
                    if (StringUtils.equals("1", content.getProblemPreType())) {
                        for (Map<String, Object> map : checkProblemList) {
                            map.put("is_selected", false);
                            if (content.getProblemContent() != null) {
                                String[] problemArr = content.getProblemContent().split("##");
                                for (String problem : problemArr) {
                                    if (problem.equals(String.valueOf(map.get("DESCRIPTION")))) {
                                        map.put("is_selected", true);
                                    }
                                }
                            }
                        }
                    }
                    content.setCheckProblemList(checkProblemList);

                }
                jgFlightStandard.setFlightContentList(flightContentList);
            }
            flightPlanCheck.setFlightStandardList(flightStandardList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取检查信息失败!");
        }
        return flightPlanCheck;
    }

    @Transactional(rollbackFor = Exception.class)
    public JgFlightPlanCheck uploadCheckFile(Long checkId, MultipartFile file) throws Exception {
        JgFlightPlanCheck dailyCheck = flightPlanCheckMapper.selectById(checkId);
        FileResultEntity fileEntity = FileUploadUtil.uploadImage(file, FileUploadEnum.flightPlan.getPath());
        try {
            dailyCheck.setComanyPic(fileEntity.getFilePath());
            dailyCheck.setComanyThumbnail(fileEntity.getFileThPath());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败");
        }
        try {
            flightPlanCheckMapper.updateById(dailyCheck);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存告知单失败");
        }
        return dailyCheck;
    }

    @Transactional(rollbackFor = Exception.class)
    public String saveCheckInform(Long checkId, String informFile) {
        JgFlightPlanCheck dailyCheck = flightPlanCheckMapper.selectById(checkId);
        if (dailyCheck == null) {
            throw new RuntimeException("请先在检查内容中进行操作");
        }
        try {
            FileResultEntity informFileUrl = FileUploadUtil.uploadImageBase64Image(informFile, FileUploadEnum.flightPlan.getPath());
            dailyCheck.setInformUrl(informFileUrl.getFilePath());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败");
        }
        try {
            flightPlanCheckMapper.updateById(dailyCheck);
            return dailyCheck.getInformUrl();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存告知单失败");
        }
    }

    /**
     * 保存/临时保存检查项结果内容
     *
     * @param temporary
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgFlightPlanCheck saveCheckInfo(String temporary, JgFlightPlanCheck flightPlanCheck) {
        TcCompany company = tcCompanyMapper.selectById(flightPlanCheck.getCompanyId());

        if ("2".equals(temporary)) {
            flightPlanCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            flightPlanCheck.setCheckStat("1");
        } else {
            flightPlanCheck.setCheckStat("3");
        }
        // 监督检查任务类型(1:日常检查、2:飞行检查、3:体系检查)
        flightPlanCheck.setInspType("2");
        flightPlanCheck.setIsSpecialItem("0");
        flightPlanCheck.setInspBose("0");
        //处理体系检查
        JgCheckResultTableSequence resultTableSequence = sequenceService.getResultTableSequence();
        Long resultRecordIndex = flightPlanCheck.getResultRecordIndex() == null ? resultTableSequence.getTableIndex() : flightPlanCheck.getResultRecordIndex();
        flightPlanCheck.setResultRecordIndex(resultRecordIndex);
        flightPlanCheck.setInspBoseName("食品生产监督检查要点表");
        //更新检查次数
        //1.按主体ID查询最新的检查次数
        Integer checkNum = flightPlanCheckMapper.queryMaxCheckNumByCheckYearAndCompanyId((DateUtil.format(new Date(), "yyyy")), company.getId());
        flightPlanCheck.setCheckNum(checkNum == null ? 1 : checkNum + 1L);
        //保存检查内容列表信息
        saveItemListAndContentList(flightPlanCheck, flightPlanCheck.getManageStatus());
        if ("1".equals(flightPlanCheck.getManageStatus())) {
            //如果选择的是异常的话
            flightPlanCheck.setProcessResults("2");
            //保存异常信息
            saveEntAnomaly(company, flightPlanCheck, temporary);
        }
        flightPlanCheckMapper.updateById(flightPlanCheck);

        //这里只做临时保存了
        return flightPlanCheck;
    }

    /**
     * 保存检查内容
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveItemListAndContentList(JgFlightPlanCheck flightPlanCheck, String manageStatus) {
        List<JgFlightStandard> flightStandardList = flightPlanCheck.getFlightStandardList();
        List<JgFlightStandard> standardUpdateList = new ArrayList<>();
        List<JgFlightContent> contentUpdateList = new ArrayList<>();
        List<JgFlightContentFile> contentFiles = new ArrayList<>();
        for (JgFlightStandard flightStandard : flightStandardList) {
            standardUpdateList.add(flightStandard);
            List<JgFlightContent> flightContentList = flightStandard.getFlightContentList();

            for (JgFlightContent flightContent : flightContentList) {
                if (StringUtils.isNotBlank(flightContent.getProblemFile()) && flightContent.getProblemFile().indexOf("data:image") >= 0) {
                    try {

                        FileResultEntity uploadEntity = FileUploadUtil.uploadImageBase64Image(flightContent.getProblemFile(), FileUploadEnum.flightPlan.getPath());
                        String filePicture = flightContent.getProblemFile();
                        flightContent.setProblemFile(uploadEntity.getFilePath());
                        //保存内容文件
                        JgFlightContentFile contentFile = new JgFlightContentFile();
                        contentFile.setFlightStandardId(flightContent.getFlightStandardId());
                        contentFile.setFlightContentId(flightContent.getId());
                        contentFile.setProblemFile(uploadEntity.getFilePath());
                        contentFile.setFilePicture(filePicture);
                        contentFile.setCreateTime(new Date());
                        contentFileMapper.insert(contentFile);
//                        contentFiles.add(contentFile);
                    } catch (Exception e) {
                        throw new RuntimeException("文件存储失败");
                    }
                }
                if (StringUtils.equals("1", manageStatus)) {
                    //经营异常 所有项都是否
                    flightContent.setSelection("2");
                }
                contentUpdateList.add(flightContent);
            }
        }
        flightStandardMapper.batchUpdate(standardUpdateList);
        flightContentMapper.batchUpdate(contentUpdateList);
//        if (contentFiles.size() > 0) {
//            contentFileMapper.batchInsert(contentFiles);
//        }


    }


    /**
     * 保存检查异常的信息
     *
     * @param company   企业信息
     * @param temporary
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveEntAnomaly(TcCompany company,
                               JgFlightPlanCheck flightPlanCheck, String temporary) {
        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(flightPlanCheck.getId(), "3");
        if (jsEntAnomaly == null) {
            jsEntAnomaly = new JsEntAnomaly();
        }
        jsEntAnomaly.setCheckType("3");
        jsEntAnomaly.setCompanyId(company.getId());
        jsEntAnomaly.setCompanyName(company.getCompanyName());
        jsEntAnomaly.setCreditCode(company.getCreditCode());
        jsEntAnomaly.setLicense(company.getLicense());
        jsEntAnomaly.setDailyCheckId(flightPlanCheck.getId());
        jsEntAnomaly.setAbnormalCause(flightPlanCheck.getAbnormalCause());
        jsEntAnomaly.setAuditTrails(flightPlanCheck.getVerificationRecords());
        jsEntAnomaly.setRectifyTime(flightPlanCheck.getRectificationTime());
        jsEntAnomaly.setCheckResults(flightPlanCheck.getCheckResult());
        jsEntAnomaly.setProcessResults(flightPlanCheck.getProcessResults());
        if (!"2".equals(temporary)) {
            //临时存储的
            jsEntAnomaly.setDeleteFlag(2L);
        } else {
            //正式存储的
            jsEntAnomaly.setDeleteFlag(0L);
        }
        int checkNum = 0;
        //修改所有的检查内容为选择的否
        List<JgFlightStandard> flightStandardList = flightPlanCheck.getFlightStandardList();
        for (JgFlightStandard flightStandard : flightStandardList) {
            List<JgFlightContent> flightContentList = flightStandard.getFlightContentList();
            checkNum = checkNum + flightContentList.size();
        }

        jsEntAnomaly.setCheckNumber(checkNum);
        if (jsEntAnomaly.getId() == null) {
            jsEntAnomaly.setCreateTime(new Date());
            jsEntAnomaly.setCreatorId(UserHelper.getUserId());
            jsEntAnomaly.setCreator(UserHelper.getUserInfo().getName());
            jsEntAnomalyMapper.insert(jsEntAnomaly);
        } else {
            jsEntAnomalyMapper.updateById(jsEntAnomaly);
        }
    }


    /**
     * 最终保存
     *
     * @param checkId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgFlightPlanCheck finaSaveInfo(Long checkId) {
        JgFlightPlanCheck dailyCheck = flightPlanCheckMapper.selectById(checkId);
        dailyCheck.setCheckStat("1");
        dailyCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        flightPlanCheckMapper.updateById(dailyCheck);
        TcCompany company = tcCompanyMapper.selectById(dailyCheck.getCompanyId());
        //如果选择的不是通过的话生成相应的后续步骤
        if ("2".equals(dailyCheck.getProcessResults())) {
            //责令整改
            saveRectification(dailyCheck.getRectificationTime(), company, dailyCheck);
        } else if ("3".equals(dailyCheck.getProcessResults())) {
            //选择调查处理同时也要生成一个整改信息
            saveRectification(dailyCheck.getRectificationTime(), company, dailyCheck);
            //调查处理,查看调查处理开关是否打开
            JgInvestigationSet investigationSet = investigationSetMapper.selectByCheckTypeAndProcess("4", company.getSupProcess());
            //调查处理开关打开的情况下才生成下面的内容
            if ("1".equals(investigationSet == null ? "2" : investigationSet.getCheckStatus())) {
                saveInvestigation(company, dailyCheck);
            }
        }


        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), "3");
        if (jsEntAnomaly != null) {
            jsEntAnomaly.setDeleteFlag(0L);
            jsEntAnomalyMapper.updateById(jsEntAnomaly);
        }

        //保存最新数据到评级的分数表，每年评级的时候要用
        List<JgFlightContent> dailyContentList = flightContentMapper.selectByCheckId(checkId);
        for (JgFlightContent dailyContentMap : dailyContentList) {
            JgScDynamicScoring jgScDynamicScoring = scDynamicScoringMapper.selectByContentIdAndCompanyId(dailyContentMap.getContentId(), dailyCheck.getCompanyId());
            if (jgScDynamicScoring == null) {
                jgScDynamicScoring = new JgScDynamicScoring();
                jgScDynamicScoring.setContentId(dailyContentMap.getContentId());
                jgScDynamicScoring.setCheckContent(dailyContentMap.getCheckContent());
                jgScDynamicScoring.setCompanyId(dailyCheck.getCompanyId());
                jgScDynamicScoring.setScore(dailyContentMap.getScore());
                jgScDynamicScoring.setSelection(dailyContentMap.getSelection());
                jgScDynamicScoring.setCreatorId(UserHelper.getUserId());
                jgScDynamicScoring.setCreatorName(UserHelper.getUserInfo().getName());
                jgScDynamicScoring.setCreateTime(new Date());
                jgScDynamicScoring.setDeleteFlag("0");
                scDynamicScoringMapper.insert(jgScDynamicScoring);
            } else {
                jgScDynamicScoring.setUpdateTime(new Date());
                jgScDynamicScoring.setUpdateName(UserHelper.getUserInfo().getName());
                jgScDynamicScoring.setUpdateId(UserHelper.getUserId());
                scDynamicScoringMapper.updateById(jgScDynamicScoring);
            }
        }
        return dailyCheck;
    }

    /**
     * 保存整改信息
     *
     * @param rectificationTimeLimit 整改期限
     * @param company                企业信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveRectification(String rectificationTimeLimit,
                                  TcCompany company, JgFlightPlanCheck flightPlanCheck) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgRectification> rectifications = rectificationMapper.selectByCheckId(flightPlanCheck.getId(), "3");
        JgRectification rectification;
        if (rectifications.size() > 0) {
            rectification = rectifications.get(0);
        } else {
            rectification = new JgRectification();
        }
        rectification.setCompanyId(company.getId());
        rectification.setCheckId(flightPlanCheck.getId());
        rectification.setCheckType("3");
        rectification.setCheckStatus("1");
        rectification.setRectificationTimeLimit(rectificationTimeLimit);
        rectification.setCreateTime(new Date());
        rectification.setCreatorId(UserHelper.getUserId());
        rectification.setCreatorName(UserHelper.getUserInfo().getName());
        rectification.setDeleteFlag(0L);
        if (rectification.getId() == null) {
            rectificationMapper.insert(rectification);
        } else {
            rectificationMapper.updateById(rectification);

        }

        //保存整改内容的初始信息
        if (!StringUtils.equals(flightPlanCheck.getManageStatus(), "1")) {
            //选择的不是经营异常才存储这个问题项
            List<JgFlightContent> flightContentList = flightContentMapper.selectNoPassByCheckId(flightPlanCheck.getId());
            List<JgRectificationContent> rectificationContents = new ArrayList<>();
            for (JgFlightContent jgDailyContent : flightContentList) {
                JgRectificationContent rectificationContent = new JgRectificationContent();
                rectificationContent.setRectificationId(rectification.getId());
                rectificationContent.setCheckType("1");
                rectificationContent.setCheckContentId(jgDailyContent.getId());
                rectificationContent.setCreateTime(new Date());
                rectificationContent.setCreatorId(UserHelper.getUserId());
                rectificationContent.setCreatorName(UserHelper.getUserInfo().getName());
                rectificationContent.setDeleteFlag(0L);
                rectificationContent.setSerialNum(jgDailyContent.getStandardNum());
                rectificationContent.setStandardName(jgDailyContent.getStandardName());
                rectificationContent.setContentNum(jgDailyContent.getSerialNum());
                rectificationContent.setCheckContent(jgDailyContent.getCheckContent());
                rectificationContent.setSelection(jgDailyContent.getSelection());
                rectificationContent.setProblemContent(jgDailyContent.getProblemContent());
                rectificationContent.setProblemFile(jgDailyContent.getProblemFile());
                rectificationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
                rectificationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());
                rectificationContent.setMissingItemContent(jgDailyContent.getMissingItemContent());
                // rectificationContentMapper.insert(rectificationContent);
                rectificationContents.add(rectificationContent);
            }
            if (!rectificationContents.isEmpty()) {
                rectificationContentMapper.batchInsert(rectificationContents);
            }
        }
    }


    /**
     * 保存调查处理
     *
     * @param company 企业信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveInvestigation(
            TcCompany company, JgFlightPlanCheck flightPlanCheck) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgInvestigation> investigations = investigationMapper.selectByCheckId(flightPlanCheck.getId(), "3");
        JgInvestigation investigation;
        if (investigations.size() > 0) {
            investigation = investigations.get(0);
        } else {
            investigation = new JgInvestigation();
        }
        investigation.setCompanyId(company.getId());
        investigation.setCheckId(flightPlanCheck.getId());
        investigation.setCheckType("3");
        investigation.setCheckStatus("1");
        investigation.setCreateTime(new Date());
        investigation.setCreatorId(UserHelper.getUserId());
        investigation.setCreatorName(UserHelper.getUserInfo().getName());
        investigation.setDeleteFlag(0L);
        investigation.setCheckPersonnel(UserHelper.getUserId());//处理人员，谁检查的就是谁
        investigation.setCheckPersonnelName(UserHelper.getUserInfo().getName());
        if (investigation.getId() == null) {
            investigationMapper.insert(investigation);
        } else {
            investigationMapper.updateById(investigation);
        }
        //保存整改内容的初始信息
        List<JgFlightContent> dailyContent = flightContentMapper.selectNoPassByCheckId(flightPlanCheck.getId());
        List<JgInvestigationContent> investigationContents = new ArrayList<>();
        for (JgFlightContent jgDailyContent : dailyContent) {
            JgInvestigationContent investigationContent = new JgInvestigationContent();
            investigationContent.setInvestigationId(investigation.getId());
            investigationContent.setCheckType("3");
            investigationContent.setCheckContentId(jgDailyContent.getId());
            investigationContent.setCreateTime(new Date());
            investigationContent.setCreatorId(UserHelper.getUserId());
            investigationContent.setCreatorName(UserHelper.getUserInfo().getName());
            investigationContent.setDeleteFlag(0L);
            investigationContent.setSerialNum(jgDailyContent.getStandardNum());
            investigationContent.setStandardName(jgDailyContent.getStandardName());
            investigationContent.setContentNum(jgDailyContent.getSerialNum());
            investigationContent.setCheckContent(jgDailyContent.getCheckContent());
            investigationContent.setSelection(jgDailyContent.getSelection());
            investigationContent.setProblemContent(jgDailyContent.getProblemContent());
            investigationContent.setProblemFile(jgDailyContent.getProblemFile());
            investigationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
            investigationContent.setMissingItemContent(jgDailyContent.getMissingItemContent());
            investigationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());
//            investigationContentMapper.insert(investigationContent);
            investigationContents.add(investigationContent);
        }
        investigationContentMapper.batchInsert(investigationContents);

    }

    /**
     * 上传结果记录的文件
     *
     * @param checkId 日常检查结果表id
     * @param imgFile 二进制文件流
     * @param type    1-要点表；2-记录表
     * @return
     */

    @Transactional(rollbackFor = Exception.class)
    public String uploadResultRecord(Long checkId, MultipartFile imgFile, String type) throws Exception {
        JgFlightPlanCheck dailyCheck = flightPlanCheckMapper.selectById(checkId);
        if (imgFile != null && StringUtils.isNoneBlank(imgFile.getOriginalFilename())) {
            FileResultEntity fileResultEntity = FileUploadUtil.uploadImage(imgFile, FileUploadEnum.flightPlan.getPath());
            if ("1".equals(type)) {
                dailyCheck.setCheckItemTableUrl(fileResultEntity.getFilePath());
            } else if ("2".equals(type)) {
                dailyCheck.setResultRecordUrl(fileResultEntity.getFilePath());
            }
            flightPlanCheckMapper.updateById(dailyCheck);
            return fileResultEntity.getFilePath();
        }
        return "";
    }


    /**
     * 查询检查信息
     *
     * @param checkId 检查id
     * @return
     */
    public JgFlightPlanCheck getCheckInfo(Long checkId) {
        JgFlightPlanCheck dailyCheck = flightPlanCheckMapper.selectById(checkId);
        QueryWrapper<JgFlightStandard> dailyStandardQueryWrapper = new QueryWrapper<>();
        dailyStandardQueryWrapper.eq("delete_flag", "0");
        dailyStandardQueryWrapper.eq("FLIGHT_PLAN_CHECK_ID", checkId);
        List<JgFlightStandard> standardList = flightStandardMapper.selectList(dailyStandardQueryWrapper);
        for (JgFlightStandard flightStandard : standardList) {
            QueryWrapper<JgFlightContent> dailyContentQueryWrapper = new QueryWrapper<>();
            dailyContentQueryWrapper.eq("delete_flag", "0");
            dailyContentQueryWrapper.eq("FLIGHT_STANDARD_ID", flightStandard.getId());
            List<JgFlightContent> contentList = flightContentMapper.selectList(dailyContentQueryWrapper);
            flightStandard.setFlightContentList(contentList);
        }
        List<JgFlightPlanUser> flightPlanUserList = flightPlanUserMapper.selectByPlanId(dailyCheck.getPlantId());
        dailyCheck.setFlightPlanUserList(flightPlanUserList);
        dailyCheck.setFlightStandardList(standardList);
        return dailyCheck;
    }

    /**
     * 获取检查结果记录
     *
     * @param checkId
     * @return
     */
    public Map<String, Object> getCheckResultInfo(Long checkId) {
        Map<String, Object> result = new HashMap<>();
        //检查结果
        Map<String, Object> checkInfo = new HashMap<>();
        //获取和各项，不合格项，合理缺项比例
        JgFlightPlanCheck dailyCheck = flightPlanCheckMapper.selectById(checkId);
        List<JgFlightPlanUser> schemePlanUser = flightPlanUserMapper.selectByPlanId(dailyCheck.getPlantId());

        List<Map<String, Object>> contentList = flightContentMapper.selectMapByCheckId(checkId);
        int hege = 0;
        int buhege = 0;
        int heliquexiang = 0;

        if ("1".equals(dailyCheck.getManageStatus())) {
            JsEntAnomaly entAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), "3");
            checkInfo.put("CHECK_RESULTS", entAnomaly.getCheckResults());
            checkInfo.put("ECHARTS_QUALIFIED", hege);
            checkInfo.put("ECHARTS_NOQUALIFIED", entAnomaly.getCheckNumber());
            checkInfo.put("ECHARTS_MISSING_ITEM", heliquexiang);
        } else {
            checkInfo.put("CHECK_RESULTS", dailyCheck.getCheckResult());
            // is '选择项：1是、2否、3合理缺项'
            for (Map<String, Object> content : contentList) {
                String selection = content.get("SELECTION") + "";
                switch (selection) {
                    case "1":
                        hege++;
                        break;
                    case "2":
                        buhege++;
                        break;
                    case "3":
                        heliquexiang++;
                        break;
                }
            }
            checkInfo.put("ECHARTS_QUALIFIED", hege);
            checkInfo.put("ECHARTS_NOQUALIFIED", buhege);
            checkInfo.put("ECHARTS_MISSING_ITEM", heliquexiang);
        }

        //处理结果：1通过检查，2责令整改，3调查处理
        checkInfo.put("PROCESS_RESULTS", dailyCheck.getProcessResults());
        checkInfo.put("CHECK_DEPT_NAME", dailyCheck.getDeptName());
        checkInfo.put("CHECK_DATE", dailyCheck.getCheckTime());
        //整改完成时限 获取整改信息
        List<JgRectification> rectificationList = rectificationMapper.selectByCheckId(dailyCheck.getId(), "3");
        checkInfo.put("RECTIFICATION_TIME_LIMIT", rectificationList.size() > 0 ? rectificationList.get(0).getRectificationTimeLimit() : "");
        //其他问题
        checkInfo.put("OTHER_PROBLEM", dailyCheck.getOtherProblem());
        //监督检查要点表url
        checkInfo.put("CHECK_ITEM_TABLEURL", dailyCheck.getCheckItemTableUrl());
        //结果记录表url
        checkInfo.put("RESULT_RECORD_URL", dailyCheck.getResultRecordUrl());  //告知页
        checkInfo.put("INFORM_URL", dailyCheck.getInformUrl());
        checkInfo.put("COMANY_PIC", dailyCheck.getComanyPic());
        checkInfo.put("MANAGE_STATUS", dailyCheck.getManageStatus());
        checkInfo.put("CHECK_TIME", dailyCheck.getCheckTime());
        checkInfo.put("userList", schemePlanUser);
        result.put("checkInfo", checkInfo);
        Map<String, Object> companyInfo = tcCompanyMapper.selectCompanyInspectionInfo(dailyCheck.getCompanyId());
        result.put("baseInfo", companyInfo);
        List<JgFlightStandard> standardList = flightStandardMapper.selectByCheckId(checkId);
        result.put("standardList", standardList);
        result.put("plantId", dailyCheck.getPlantId());
        return result;

    }

    /**
     * 获取检查结果中点击检查项目的时候显示详细项列表
     *
     * @param dailyStandardId
     * @return
     */
    public List<JgFlightContent> getCheckContentList(Long dailyStandardId) {
        JgFlightStandard flightStandard = flightStandardMapper.selectById(dailyStandardId);
        JgFlightPlanCheck flightPlanCheck = flightPlanCheckMapper.selectById(flightStandard.getFlightPlanCheckId());
        //风险信息
        Map<String, String> riskMap = baseDataService.riskInfo(flightPlanCheck.getCompanyId());
        List<String> riskCode = new ArrayList<>();
        Set<String> riskKeySet = riskMap.keySet();
        for (String riskKey : riskKeySet) {
            if (!riskMap.get(riskKey).equals("0")) {
                riskCode.add(riskKey);
            }
        }
        return flightContentMapper.selectByStandardId(dailyStandardId, riskCode);

    }


    /**
     * 查询结果表需要的数据
     *
     * @param checkId 日常检查表JG_DAILY_CHECK  id
     * @return
     */
    public Map<String, Object> getResultTable(Long checkId) {
        Map<String, Object> checkInfo = flightPlanCheckMapper.selectMapById(checkId);
        List<Map<String, Object>> contentList = flightContentMapper.selectMapByCheckId(checkId);
        Integer contentNum = contentList.size();
        Integer importNum = 0; //重点项
        Integer importProblemNum = 0; //发现问题
        Integer commonlyNum = 0; //一般项
        Integer commonlyProblemNum = 0; //发现问题
        List<String> importNo = new ArrayList<>();//重点项序号
        List<String> importProblemNo = new ArrayList<>();//重点项序号
        List<String> commonlyNo = new ArrayList<>();//一般项序号
        List<String> commonlyProblemNo = new ArrayList<>();//一般项序号
        Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)?");
        for (Map<String, Object> content : contentList) {
            //IMPORTENT_ITEM is '重要项：1一般项，2重要项
            //SELECTION is '选择项：1是、2否、3合理缺项
            if (StringUtils.equals(content.get("IMPORTENT_ITEM") + "", "1")) {
                commonlyNum = commonlyNum + 1;
                Matcher matcher = pattern.matcher(content.get("CHECK_CONTENT").toString());
                Matcher dxmatcher = pattern.matcher(content.get("DX_SERIAL_NUM").toString());
                String dxNumber = (dxmatcher.find() && StringUtils.isNotBlank(dxmatcher.group())) ? dxmatcher.group() : content.get("DX_SERIAL_NUM") + "";
                if (matcher.find() && StringUtils.isNotBlank(matcher.group())) {
                    String number = matcher.group();
                    commonlyProblemNo.add(dxNumber + "." + number);
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        commonlyProblemNo.add(dxNumber + "." + number);
                    }
                } else {
                    //如果内容文字不匹配则查询序号字段
                    commonlyNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        commonlyProblemNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    }
                }
                if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                    commonlyProblemNum = commonlyProblemNum + 1;
                }

            } else if (StringUtils.equals(content.get("IMPORTENT_ITEM") + "", "2")) {
                importNum = importNum + 1;
                Matcher matcher = pattern.matcher(content.get("CHECK_CONTENT").toString());
                if (matcher.find() && StringUtils.isNotBlank(matcher.group())) {
                    Matcher dxmatcher = pattern.matcher(content.get("DX_SERIAL_NUM").toString());
                    String dxNumber = (dxmatcher.find() && StringUtils.isNotBlank(dxmatcher.group())) ? dxmatcher.group() : content.get("DX_SERIAL_NUM") + "";
                    String number = matcher.group();
                    importNo.add(dxNumber + "." + number);
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        importProblemNo.add(dxNumber + "." + number);
                    }
                } else {
                    //如果内容文字不匹配则查询序号字段
                    importNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        importProblemNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    }
                }
                if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                    importProblemNum = importProblemNum + 1;
                }
            }
        }
        if (checkInfo.get("CHECK_PERSON1_ID") != null) {
            TsUser user1 = userMapper.selectById(Integer.valueOf(checkInfo.get("CHECK_PERSON1_ID").toString()));
            checkInfo.put("enforcementNo1", user1.getEnforcementNo());
            checkInfo.put("enforcementName1", user1.getName());
        }
        if (checkInfo.get("CHECK_PERSON2_ID") != null) {
            TsUser user2 = userMapper.selectById(Integer.valueOf(checkInfo.get("CHECK_PERSON2_ID").toString()));
            checkInfo.put("enforcementNo2", user2.getEnforcementNo());
            checkInfo.put("enforcementName2", user2.getName());
        }
  /*      QueryWrapper<JgFlightPlanCheck> flightPlanCheckQueryWrapper = new QueryWrapper<>();
        flightPlanCheckQueryWrapper.eq("delete_flag","0");
        flightPlanCheckQueryWrapper.eq("CHECK_STAT", "1");
        flightPlanCheckQueryWrapper.eq("company_id",checkInfo.get("COMPANY_ID"));
        flightPlanCheckQueryWrapper.eq("date_format(CHECK_TIME,'%Y')",DateUtil.year(new Date()));
        Long flightPlanCheckCount = flightPlanCheckMapper.selectCount(flightPlanCheckQueryWrapper);

        QueryWrapper<JgSchemePlanCheck> schemePlanCheckQueryWrapper = new QueryWrapper<>();
        schemePlanCheckQueryWrapper.eq("delete_flag","0");
        flightPlanCheckQueryWrapper.eq("CHECK_STAT", "1");
        schemePlanCheckQueryWrapper.eq("company_id",checkInfo.get("COMPANY_ID"));
        schemePlanCheckQueryWrapper.eq("date_format(CHECK_TIME,'%Y')",DateUtil.year(new Date()));
        Long schemePlanCheckCount = schemePlanCheckMapper.selectCount(schemePlanCheckQueryWrapper);

        QueryWrapper<JgDailyCheck> jgDailyCheckQueryWrapper = new QueryWrapper<>();
        jgDailyCheckQueryWrapper.eq("delete_flag","0");
        jgDailyCheckQueryWrapper.eq("CHECK_STAT", "1");
        jgDailyCheckQueryWrapper.eq("company_id",checkInfo.get("COMPANY_ID"));
        jgDailyCheckQueryWrapper.eq("CHECK_YEAR",DateUtil.year(new Date()));
        Long dailyCheckCount = dailyCheckMapper.selectCount(jgDailyCheckQueryWrapper);
*/
//        checkInfo.put("CHECK_NUM", flightPlanCheckCount + schemePlanCheckCount + dailyCheckCount + 1 );
        checkInfo.put("contentNum", contentNum);
        checkInfo.put("importNum", importNum);
        checkInfo.put("importProblemNum", importProblemNum);
        checkInfo.put("commonlyNum", commonlyNum);
        checkInfo.put("commonlyProblemNum", commonlyProblemNum);
        checkInfo.put("importNo", String.join(" ; ", importNo));
        checkInfo.put("importProblemNo", String.join(" ; ", importProblemNo));
        checkInfo.put("commonlyNo", String.join(" ; ", commonlyNo));
        checkInfo.put("commonlyProblemNo", String.join(" ; ", commonlyProblemNo));

        //生成单子编号
        JgFlightPlanCheck flightPlanCheck = flightPlanCheckMapper.selectById(checkId);
        //检查单今年的流水号
        if (flightPlanCheck.getResultRecordIndex() == null) {
            //当前单子未生成过.如果第二次保存结果记录表，则直接使用第一次的序号来生成
            JgCheckResultTableSequence resultTableSequence = sequenceService.getResultTableSequence();
            flightPlanCheck.setResultRecordIndex(resultTableSequence.getTableIndex());//加一并获取
            flightPlanCheckMapper.updateById(flightPlanCheck);
        }
        //序号按照6位数在签名补0
        Long index = flightPlanCheck.getResultRecordIndex();
        String resultCode = SequenceService.generatorProResultTableCode(index);
        checkInfo.put("resultCode", resultCode);
        return checkInfo;
    }

    public List<JgFlightPlanUser> getFlightSupervisePersonList(Long plantId) {
        return flightPlanUserMapper.selectByPlanId(plantId);
    }
}
